package com.example.image;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class BitmapUtils {

    private static final String TAG = "BitmapUtils";

    public void test(Context context) {
//        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.mipmap.big_img);

        //            byte[] bytes = new byte[1 * 1024 * 1024];
//            int size =  getAssets().open("test_img.jpeg").read(bytes);
//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inSampleSize = 2;
//            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, size, options);

        //            byte[] bytes = new byte[1 * 1024 * 1024];
//            int size =  getAssets().open("test_img.jpeg").read(bytes);
//            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, size);

//        Bitmap targetBitmap = Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(targetBitmap);
//        iv1.draw(canvas);
    }

    public void saveToPNG(Bitmap targetBitmap) {

        File targetFile = new File(Environment.getExternalStorageDirectory() + "测试图片夹/" + System.currentTimeMillis() + ".png");
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        try {
            FileWriter writer = new FileWriter(targetFile);
            BufferedWriter bufferedWriter = new BufferedWriter(writer);
//            bufferedWriter.
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void showInfo(Bitmap bitmap) {
        Log.d(TAG, "占用内存大小：" + (getMemorySize(bitmap)) + " kb");
        Log.d(TAG, "计算占用内存大小：" + (calculateMemorySize(bitmap)) + " kb");

    }

    private float getMemorySize(Bitmap bitmap) {
        int result = 0;
        //Since API 19
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            result = bitmap.getAllocationByteCount();
        } else {
            result = bitmap.getByteCount();
        }
        return result*1f/1024f;

    }

    private float calculateMemorySize(Bitmap bitmap) {
        int pixels = bitmap.getWidth() * bitmap.getHeight();
        int bytes = 0;
        switch (bitmap.getConfig()) {
            case ALPHA_8:pixels *= 1;break;
            case ARGB_4444:
            case RGB_565:
                pixels *= 2;break;
            case ARGB_8888:
            default:pixels *= 4;break;
        }
        bytes = pixels;
        return bytes*1f/1024f;
    }

}
